import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  Button,
  Input,
  Label,
  Text,
  Spinner,
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
} from 'packages/ui-shared/src/atoms';
import {
  AuditLogService,
  AuditLog,
  AuditAction,
  AuditLogQuery,
  AuditLogStats,
} from '@packages/shared';

export default function AuditLogPage() {  const navigate = useNavigate();  const location = useLocation();  const pathname = location.pathname;  const isStatsView = pathname.includes('/stats');
  // Mock 数据
  const mockLogs: AuditLog[] = [
    {
      id: '1',
      timestamp: new Date(Date.now() - 1000 * 60 * 5).toISOString(),
      userId: '101',
      userName: '张三',
      userRole: 'admin',
      action: 'login',
      description: '用户登录系统',
      ipAddress: '192.168.1.100',
      status: 'success'
    },
    {
      id: '2',
      timestamp: new Date(Date.now() - 1000 * 60 * 15).toISOString(),
      userId: '102',
      userName: '李四',
      userRole: 'user',
      action: 'update_classroom',
      description: '更新教室信息',
      ipAddress: '192.168.1.101',
      status: 'success'
    },
    {
      id: '3',
      timestamp: new Date(Date.now() - 1000 * 60 * 30).toISOString(),
      userId: '103',
      userName: '王五',
      userRole: 'user',
      action: 'add_student',
      description: '添加新学生',
      ipAddress: '192.168.1.102',
      status: 'success'
    },
    {
      id: '4',
      timestamp: new Date(Date.now() - 1000 * 60 * 60).toISOString(),
      userId: '104',
      userName: '赵六',
      userRole: 'guest',
      action: 'login',
      description: '用户登录系统',
      ipAddress: '192.168.1.103',
      status: 'failed'
    },
    {
      id: '5',
      timestamp: new Date(Date.now() - 1000 * 60 * 120).toISOString(),
      userId: '101',
      userName: '张三',
      userRole: 'admin',
      action: 'update_user',
      description: '更新用户信息',
      ipAddress: '192.168.1.100',
      status: 'success'
    }
  ];

  const mockStats: AuditLogStats = {
    totalLogs: 125,
    loginCount: 45,
    failedLoginCount: 5,
    userActions: 75,
    adminActions: 30,
    recentActivity: [
      {
        id: '1',
        userName: '张三',
        description: '用户登录系统',
        timestamp: new Date(Date.now() - 1000 * 60 * 5).getTime(),
        success: true
      },
      {
        id: '2',
        userName: '李四',
        description: '更新教室信息',
        timestamp: new Date(Date.now() - 1000 * 60 * 15).getTime(),
        success: true
      },
      {
        id: '3',
        userName: '王五',
        description: '添加新学生',
        timestamp: new Date(Date.now() - 1000 * 60 * 30).getTime(),
        success: true
      },
      {
        id: '4',
        userName: '赵六',
        description: '用户登录系统',
        timestamp: new Date(Date.now() - 1000 * 60 * 60).getTime(),
        success: false
      },
      {
        id: '5',
        userName: '张三',
        description: '更新用户信息',
        timestamp: new Date(Date.now() - 1000 * 60 * 120).getTime(),
        success: true
      }
    ]
  };

  const [logs, setLogs] = useState<AuditLog[]>(mockLogs);
  const [stats, setStats] = useState<AuditLogStats | null>(mockStats);
  const [loading, setLoading] = useState(false);
  const [showStats, setShowStats] = useState(false);
  const [showExport, setShowExport] = useState(false);
  const [query, setQuery] = useState<AuditLogQuery>({
    limit: 50,
    offset: 0,
  });

  // 获取当前用户信息（使用mock数据以便预览）
  const currentUserRole = 
    (sessionStorage.getItem('role') as 'admin' | 'user' | 'guest') || 'admin';
  
  // 设置默认的模拟用户数据
  const mockUser = {
    id: '101',
    name: '张三',
    role: 'admin'
  };
  
  const currentUser = JSON.parse(sessionStorage.getItem('user') || JSON.stringify(mockUser));
  const currentUserId = currentUser?.id;

  // 检查权限
  const canViewAuditLogs =
    currentUserRole === 'admin' || currentUserRole === 'user';

  useEffect(() => {
    if (!canViewAuditLogs) {
      navigate('/app');
      return;
    }
    loadLogs();
    loadStats();
  }, [canViewAuditLogs, navigate]);

  // 加载审计日志
  const loadLogs = async () => {
    setLoading(true);
    try {
      const logsData = await AuditLogService.queryLogs(
        query,
        currentUserRole,
        currentUserId
      );
      setLogs(logsData);
    } catch (error) {
      console.error('加载审计日志失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 加载统计信息
  const loadStats = async () => {
    try {
      const statsData = await AuditLogService.getStats(
        currentUserRole,
        currentUserId
      );
      setStats(statsData);
    } catch (error) {
      console.error('加载统计信息失败:', error);
    }
  };

  useEffect(() => {
    if (canViewAuditLogs) {
      loadLogs();
      loadStats();
    }
  }, [query, currentUserRole, currentUserId, canViewAuditLogs]);

  // 导出日志
  const handleExport = async () => {
    try {
      const csvData = await AuditLogService.exportLogs(
        currentUserRole,
        currentUserId
      );
      const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute(
        'download',
        `audit_logs_${new Date().toISOString().split('T')[0]}.csv`
      );
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      setShowExport(false);
    } catch (error) {
      console.error('导出失败:', error);
    }
  };

  // 清空日志（仅管理员）
  const handleClearLogs = async () => {
    if (currentUserRole === 'admin') {
      if (confirm('确定要清空所有审计日志吗？此操作不可恢复！')) {
        await AuditLogService.clearAllLogs();
        loadLogs();
        loadStats();
      }
    }
  };

  // 清理过期日志（仅管理员）
  const handleCleanExpiredLogs = async () => {
    if (currentUserRole === 'admin') {
      await AuditLogService.cleanExpiredLogs();
      loadLogs();
      loadStats();
    }
  };

  // 格式化时间
  const formatTime = (timestamp: number) => {
    return new Date(timestamp).toLocaleString('zh-CN');
  };

  // 获取操作类型显示名称
  const getActionDisplayName = (action: string) => {
    const actionMap: Record<string, string> = {
      [AuditAction.LOGIN]: '登录',
      [AuditAction.LOGOUT]: '登出',
      [AuditAction.LOGIN_FAILED]: '登录失败',
      [AuditAction.USER_CREATE]: '创建用户',
      [AuditAction.USER_UPDATE]: '更新用户',
      [AuditAction.USER_DELETE]: '删除用户',
      [AuditAction.ROLE_ASSIGN]: '分配角色',
      [AuditAction.PASSWORD_RESET]: '重置密码',
      [AuditAction.MFA_VERIFY]: 'MFA验证',
      [AuditAction.DATA_VIEW]: '查看数据',
      [AuditAction.DATA_EXPORT]: '导出数据',
      [AuditAction.SYSTEM_ACCESS]: '系统访问',
    };
    return actionMap[action] || action;
  };

  // 获取状态颜色
  const getStatusColor = (success: boolean) => {
    return success ? 'text-green-600' : 'text-red-600';
  };

  // 获取角色颜色
  const getRoleColor = (role: string) => {
    switch (role) {
      case 'admin':
        return 'text-red-500 font-bold';
      case 'user':
        return 'text-blue-500 font-semibold';
      case 'guest':
        return 'text-gray-500 font-normal';
      default:
        return 'text-gray-500';
    }
  };

  if (!canViewAuditLogs) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 页面头部 */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-4">
            <div className="flex items-center space-x-4">
              <Button
                variant="outline"
                onClick={() => navigate('/app')}
                className="flex items-center space-x-2"
              >
                <svg
                  className="w-4 h-4"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M15 19l-7-7 7-7"
                  />
                </svg>
                <span>返回</span>
              </Button>
              <div>
                <Text className="text-2xl font-bold text-gray-900">
                  审计日志
                </Text>
                <Text className="text-sm text-gray-600">
                  {currentUserRole === 'admin'
                    ? '查看所有用户操作记录'
                    : '查看您的操作记录'}
                </Text>
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <Text className="text-sm text-gray-600">
                当前用户：
                <span className="font-semibold">{currentUser?.name}</span>
                <span className={`ml-2 ${getRoleColor(currentUserRole)}`}>
                  {currentUserRole === 'admin'
                    ? '管理员'
                    : currentUserRole === 'user'
                    ? '用户'
                    : '访客'}
                </span>
              </Text>
            </div>
          </div>
        </div>
      </div>

      {/* 页面内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="space-y-6">
          {/* 统计信息卡片 */}
          {stats && (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="bg-white p-6 rounded-lg shadow hover:shadow-md transition-shadow duration-300 border border-gray-100">
                <div className="flex items-center">
                  <div className="flex-shrink-0 p-3 bg-blue-50 rounded-full">
                    <svg
                      className="h-8 w-8 text-blue-600"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                      />
                    </svg>
                  </div>
                  <div className="ml-4">
                    <Text className="text-sm font-medium text-gray-600">
                      总日志数
                    </Text>
                    <Text className="text-2xl font-bold text-gray-900">
                      {stats.totalLogs}
                    </Text>
                  </div>
                </div>
              </div>
              <div className="bg-white p-6 rounded-lg shadow hover:shadow-md transition-shadow duration-300 border border-gray-100">
                <div className="flex items-center">
                  <div className="flex-shrink-0 p-3 bg-green-50 rounded-full">
                    <svg
                      className="h-8 w-8 text-green-600"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                      />
                    </svg>
                  </div>
                  <div className="ml-4">
                    <Text className="text-sm font-medium text-gray-600">
                      登录次数
                    </Text>
                    <Text className="text-2xl font-bold text-green-600">
                      {stats.loginCount}
                    </Text>
                  </div>
                </div>
              </div>
              <div className="bg-white p-6 rounded-lg shadow hover:shadow-md transition-shadow duration-300 border border-gray-100">
                <div className="flex items-center">
                  <div className="flex-shrink-0 p-3 bg-red-50 rounded-full">
                    <svg
                      className="h-8 w-8 text-red-600"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L4.268 19.5c-.77.833.192 2.5 1.732 2.5z"
                      />
                    </svg>
                  </div>
                  <div className="ml-4">
                    <Text className="text-sm font-medium text-gray-600">
                      登录失败
                    </Text>
                    <Text className="text-2xl font-bold text-red-600">
                      {stats.failedLoginCount}
                    </Text>
                  </div>
                </div>
              </div>
              <div className="bg-white p-6 rounded-lg shadow hover:shadow-md transition-shadow duration-300 border border-gray-100">
                <div className="flex items-center">
                  <div className="flex-shrink-0 p-3 bg-purple-50 rounded-full">
                    <svg
                      className="h-8 w-8 text-purple-600"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                      />
                    </svg>
                  </div>
                  <div className="ml-4">
                    <Text className="text-sm font-medium text-gray-600">
                      用户操作
                    </Text>
                    <Text className="text-2xl font-bold text-purple-600">
                      {stats.userActions}
                    </Text>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* 操作按钮 */}
          <div className="bg-white p-4 rounded-lg shadow border border-gray-100">
            <div className="flex flex-wrap gap-2">
              <Button variant="secondary" onClick={() => setShowStats(true)} className="hover:bg-gray-200 transition-colors duration-200">
                查看详细统计
              </Button>
              <Button variant="primary" onClick={() => setShowExport(true)} className="bg-blue-600 hover:bg-blue-700 transition-colors duration-200">
                导出日志
              </Button>
              {currentUserRole === 'admin' && (
                <>
                  <Button variant="secondary" onClick={handleCleanExpiredLogs} className="hover:bg-gray-200 transition-colors duration-200">
                    清理过期日志
                  </Button>
                  <Button variant="danger" onClick={handleClearLogs} className="bg-red-600 hover:bg-red-700 transition-colors duration-200">
                    清空所有日志
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* 查询条件 */}
          <div className="bg-white p-6 rounded-lg shadow border border-gray-100">
            <Text className="text-lg font-semibold mb-4 text-gray-800">查询条件</Text>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <Label className="block text-sm font-medium text-gray-700 mb-1">操作类型</Label>
                <select
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 px-3 py-2 border"
                  value={query.action || ''}
                  onChange={(e) =>
                    setQuery((prev) => ({
                      ...prev,
                      action: (e.target.value as AuditAction) || undefined,
                    }))
                  }
                >
                  <option value="">全部</option>
                  {Object.values(AuditAction).map((action) => (
                    <option key={action} value={action}>
                      {getActionDisplayName(action)}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <Label className="block text-sm font-medium text-gray-700 mb-1">开始时间</Label>
                <Input
                  type="datetime-local"
                  value={
                    query.startDate
                      ? new Date(query.startDate).toISOString().slice(0, 16)
                      : ''
                  }
                  onChange={(e) =>
                    setQuery((prev) => ({
                      ...prev,
                      startDate: e.target.value
                        ? new Date(e.target.value).getTime()
                        : undefined,
                    }))
                  }
                  className="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
              </div>
              <div>
                <Label className="block text-sm font-medium text-gray-700 mb-1">结束时间</Label>
                <Input
                  type="datetime-local"
                  value={
                    query.endDate
                      ? new Date(query.endDate).toISOString().slice(0, 16)
                      : ''
                  }
                  onChange={(e) =>
                    setQuery((prev) => ({
                      ...prev,
                      endDate: e.target.value
                        ? new Date(e.target.value).getTime()
                        : undefined,
                    }))
                  }
                  className="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
              </div>
            </div>
            <div className="mt-6 flex gap-3 justify-end">
              <Button variant="secondary" onClick={() => setQuery({ limit: 50, offset: 0 })} className="hover:bg-gray-200 transition-colors duration-200">
                重置
              </Button>
              <Button variant="primary" onClick={loadLogs} className="bg-blue-600 hover:bg-blue-700 transition-colors duration-200">
                查询
              </Button>
            </div>
          </div>

          {/* 日志列表 */}
          <div className="bg-white rounded-lg shadow border border-gray-100 overflow-hidden transition-all duration-300">
            <div className="px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-white">
              <Text className="text-lg font-semibold text-gray-800">操作记录</Text>
            </div>

            {loading ? (
              <div className="flex justify-center items-center py-16">
                <div className="flex flex-col items-center">
                  <Spinner className="h-8 w-8 text-blue-600" />
                  <Text className="mt-3 text-gray-600">正在加载日志...</Text>
                </div>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <Table className="min-w-full divide-y divide-gray-200">
                  <TableHeader className="bg-gradient-to-r from-gray-50 to-gray-100">
                    <TableRow>
                      <TableHead className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        时间
                      </TableHead>
                      <TableHead className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        用户
                      </TableHead>
                      <TableHead className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        角色
                      </TableHead>
                      <TableHead className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        操作
                      </TableHead>
                      <TableHead className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        描述
                      </TableHead>
                      <TableHead className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        IP地址
                      </TableHead>
                      <TableHead className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        状态
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody className="bg-white divide-y divide-gray-200">
                    {logs.map((log) => (
                      <TableRow 
                        key={log.id} 
                        className="hover:bg-blue-50 transition-colors duration-200 cursor-pointer"
                      >
                        <TableCell className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
                          {formatTime(log.timestamp)}
                        </TableCell>
                        <TableCell className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                          {log.userName}
                        </TableCell>
                        <TableCell className="px-6 py-4 whitespace-nowrap text-sm">
                          <span className={getRoleColor(log.userRole)}>
                            {log.userRole === 'admin' ? '管理员' : log.userRole === 'user' ? '用户' : '访客'}
                          </span>
                        </TableCell>
                        <TableCell className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                          {getActionDisplayName(log.action)}
                        </TableCell>
                        <TableCell className="px-6 py-4 text-sm text-gray-600 max-w-xs">
                          <div className="truncate" title={log.description}>{log.description}</div>
                        </TableCell>
                        <TableCell className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {log.ipAddress}
                        </TableCell>
                        <TableCell className="px-6 py-4 whitespace-nowrap text-sm">
                          <span
                            className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full transition-colors duration-200 ${log.success ? 'bg-green-100 text-green-800 hover:bg-green-200' : 'bg-red-100 text-red-800 hover:bg-red-200'}`}
                          >
                            {log.success ? '成功' : '失败'}
                          </span>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}

            {logs.length === 0 && !loading && (
              <div className="text-center py-16 text-gray-500 bg-gray-50">
                <div className="inline-flex items-center justify-center p-4 bg-gray-100 rounded-full mb-4">
                  <svg
                    className="h-12 w-12 text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                    />
                  </svg>
                </div>
                <Text className="mt-2 text-lg font-medium text-center text-gray-700">
                  暂无审计日志
                </Text>
                <Text className="text-sm text-center max-w-md mx-auto mt-1">
                  当前查询条件下没有找到相关记录，请尝试调整查询条件
                </Text>
                <Button 
                  variant="secondary" 
                  onClick={() => setQuery({ limit: 50, offset: 0 })} 
                  className="mt-4 hover:bg-gray-200 transition-colors duration-200"
                >
                  重置查询条件
                </Button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 统计详情对话框 */}
      <Dialog open={showStats} onOpenChange={setShowStats}>
        <DialogContent size="lg">
          <DialogHeader>
            <DialogTitle className="text-xl font-bold text-gray-800">审计日志统计详情</DialogTitle>
          </DialogHeader>
          {stats && (
            <div className="py-4 space-y-6 animate-fadeIn">
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <div className="bg-gradient-to-br from-gray-50 to-blue-50 p-4 rounded-lg border border-blue-100 hover:shadow-md transition-all duration-300">
                  <Text className="text-sm font-medium text-gray-600">总日志数</Text>
                  <Text className="text-2xl font-bold text-gray-900 mt-1">{stats.totalLogs}</Text>
                </div>
                <div className="bg-gradient-to-br from-gray-50 to-green-50 p-4 rounded-lg border border-green-100 hover:shadow-md transition-all duration-300">
                  <Text className="text-sm font-medium text-gray-600">登录次数</Text>
                  <Text className="text-2xl font-bold text-green-600 mt-1">
                    {stats.loginCount}
                  </Text>
                </div>
                <div className="bg-gradient-to-br from-gray-50 to-red-50 p-4 rounded-lg border border-red-100 hover:shadow-md transition-all duration-300">
                  <Text className="text-sm font-medium text-gray-600">登录失败</Text>
                  <Text className="text-2xl font-bold text-red-600 mt-1">
                    {stats.failedLoginCount}
                  </Text>
                </div>
                <div className="bg-gradient-to-br from-gray-50 to-purple-50 p-4 rounded-lg border border-purple-100 hover:shadow-md transition-all duration-300">
                  <Text className="text-sm font-medium text-gray-600">用户操作</Text>
                  <Text className="text-2xl font-bold text-purple-600 mt-1">
                    {stats.userActions}
                  </Text>
                </div>
                <div className="bg-gradient-to-br from-gray-50 to-orange-50 p-4 rounded-lg border border-orange-100 hover:shadow-md transition-all duration-300">
                  <Text className="text-sm font-medium text-gray-600">管理员操作</Text>
                  <Text className="text-2xl font-bold text-orange-600 mt-1">
                    {stats.adminActions}
                  </Text>
                </div>
              </div>

              <div className="bg-gray-50 rounded-lg p-5 border border-gray-200">
                <Text className="font-semibold text-gray-800 mb-3 flex items-center">
                  <svg className="h-5 w-5 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  最近活动
                </Text>
                <div className="space-y-2 max-h-72 overflow-y-auto">
                  {stats.recentActivity.map((log) => (
                    <div
                      key={log.id}
                      className="flex justify-between items-center p-3 bg-white rounded-lg border border-gray-200 hover:bg-blue-50 transition-colors duration-200"
                    >
                      <div className="flex items-center space-x-3">
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center ${log.success ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'}`}>
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
                          </svg>
                        </div>
                        <div>
                          <Text className="text-sm font-medium text-gray-900">
                            {log.userName}
                          </Text>
                          <Text className="text-xs text-gray-600 truncate max-w-xs">
                            {log.description}
                          </Text>
                        </div>
                      </div>
                      <div className="text-right">
                        <Text className="text-xs text-gray-500">
                          {formatTime(log.timestamp)}
                        </Text>
                        <Text
                          className={`text-xs ${getStatusColor(log.success)}`}
                        >
                          {log.success ? '成功' : '失败'}
                        </Text>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
          <DialogFooter className="border-t border-gray-200 pt-4">
            <DialogClose className="bg-gray-200 hover:bg-gray-300 transition-colors duration-200">关闭</DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 导出确认对话框 */}
      <Dialog open={showExport} onOpenChange={setShowExport}>
        <DialogContent size="sm">
          <DialogHeader>
            <DialogTitle>导出审计日志</DialogTitle>
            <DialogDescription>
              确定要导出审计日志吗？将下载CSV格式文件。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <DialogClose>取消</DialogClose>
            <Button variant="primary" onClick={handleExport}>
              确认导出
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}